package production.practice.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.SecureRandom;

/**
 * id生成器
 */
public class IdGenerator {
    protected Logger logger = LoggerFactory.getLogger(IdGenerator.class);
    private long baseId;
    private static IdGenerator idGenerator = null;

    public static IdGenerator createGenerator() {
        if (null == idGenerator) {
            idGenerator = new IdGenerator();
        }

        return idGenerator;
    }

    private IdGenerator() {
        long t = System.currentTimeMillis();
        this.baseId = t;
        this.baseId &= 137170518016L;
        this.baseId <<= 16;
        t &= 268419072L;
        t <<= 2;
        this.baseId |= t;
        SecureRandom ng = new SecureRandom();
        t = ng.nextLong();
        t &= 4397778075648L;
        t <<= 2;
        this.baseId |= t;
        this.baseId /= 50000L;
        this.baseId *= 50000L;
        this.baseId &= 9007199254740991L;
    }

    public synchronized long getID() {
        return (long)(this.baseId++);
    }

    public synchronized String getBatchID(long batch) {
        String idStartEnd = this.baseId + "-" + (this.baseId + batch - 1L);
        this.baseId += batch;
        return idStartEnd;
    }
}